<template>
  <div>
    <div class="personal-home">
      <div class="section-container">
        <div v-for="(section, index) in getCurrentPageSections" :key="index" class="section" style="font-size: 21px;
    color: #5505eb;" @click="openEditModal(index)">
          <span class="section-text">{{ section.text }}</span>
        </div>
      </div>
      
      <div class="back-home-button" :style="{ opacity: showModal ? '0' : '1', visibility: showModal ? 'hidden' : 'visible' }">
        <a @click="goToHome" class="action-button">
          <span class="button-content">主页</span>
          <span class="button-glow"></span>
          <span class="button-hover"></span>
        </a>
        <a @click="openAddModal" class="action-button add">
          <span class="button-content">添加</span>
          <span class="button-glow"></span>
          <span class="button-hover"></span>
        </a>
      </div>

      <!-- 新增：添加模态框 -->
      <div v-if="showAddModal" class="modal">
        <div class="modal-content">
          <textarea v-model="addContent"></textarea>
          <div class="modal-buttons">
            <button @click="saveNewSection">保存</button>
            <button @click="closeAddModal">取消</button>
          </div>
        </div>
      </div>

      <!-- 新增：编辑模态框 -->
      <div v-if="showEditModal" class="modal">
        <div class="modal-content">
          <textarea v-model="editContent"></textarea>
          <div class="modal-buttons">
            <button @click="deleteSection">删除</button>
            <button @click="saveEdit">保存</button>
            <button @click="closeEditModal">取消</button>
          </div>
        </div>
      </div>

      <!-- 新增分页按钮 -->
      <div class="pagination" :style="{ opacity: showModal ? '0' : '1', visibility: showModal ? 'hidden' : 'visible' }">
        <button class="sortpage" @click="prevPage" :disabled="currentPage === 1">
          上一页
        </button>
        <button class="sortpage" @click="nextPage" :disabled="currentPage === totalPages">
          下一页
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import {ElMessage} from "element-plus";

export default {
  data() {
    return {
      currentPage: 1,
      pageSize: 4, // 每页显示4个section
      sections: [],
      showEditModal: false,
      editContent: '',
      currentSectionIndex: null,
      showAddModal: false,
      addContent: '',
      isAdmin: false // 新增：用于判断用户是否是管理员
    };
  },
  computed: {
    totalPages() {
      return Math.ceil(this.sections.length / this.pageSize);
    },
    getCurrentPageSections() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.sections.slice(start, end);
    },
    showModal() {
      return this.showEditModal || this.showAddModal;
    }
  },
  methods: {
    goToHome() {
      this.$router.push({name: 'Blog'});
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    },
    openEditModal(index) {
      if (!this.isAdmin) {
        ElMessage.warning('普通用户无权限修改');
        return;
      }
      const start = (this.currentPage - 1) * this.pageSize;
      const actualIndex = start + index;
      this.currentSectionIndex = actualIndex;
      // 将原文本传入到textarea中
      this.editContent = this.sections[actualIndex].text;
      this.showEditModal = true;
      // 隐藏翻页按钮
      document.querySelector('.pagination').style.display = 'none';
      this.currentSectionId = this.sections[actualIndex].id;
    },
    closeEditModal() {
      this.showEditModal = false;
      // 显示翻页按钮并恢复其样式
      const paginationElement = document.querySelector('.pagination');
      paginationElement.style.display = 'flex';
      paginationElement.style.justifyContent = 'center'; // 确保居中对齐

      // 显示返回首页按钮并恢复其样式F
      const backHomeButton = document.querySelector('.back-home-button');
      backHomeButton.style.display = 'flex';
      backHomeButton.style.justifyContent = 'flex-end';
      backHomeButton.style.alignItems = 'flex-start';
    },
    saveEdit() {
      if (this.currentSectionIndex !== null) {
        this.sections[this.currentSectionIndex].text = this.editContent; // 修改: 将 content 改为 text
        // 调用API保存修改到数据库
        this.saveSectionToDatabase(this.sections[this.currentSectionIndex]);
      }
      this.closeEditModal();
    },
    fetchSections() {
      axios.get('/api/sections', {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken') // 确保 JWT 令牌被添加到请求头
        }
      })
          .then(response => {
            if (response.data && Array.isArray(response.data)) {
              this.sections = response.data.map(section => ({
                ...section,
                text: section.text || '' // 修改: 确保 text 存在
              }));
            } else {
             ElMessage.error('获取失败,请检查网络连接或重新登录');
            }
          })
          .catch(error => {
            ElMessage.error('获取失败,请检查网络连接或重新登录');
          });
    },
    saveSectionToDatabase(section) {
      console.log(localStorage.getItem('jwtToken'));
      axios.post('/api/sections/update', {id: section.id, text: section.text}, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken') // 确保 JWT 令牌被添加到请求头
        }
      })
          .then(response => {
            ElMessage.success('修改成功');
          })
          .catch(error => {
            ElMessage.error('修改失败,请检查网络连接或重新登录');
          });
    },
    deleteSection() { // 删除：旧的参数 section
      axios.delete(`/api/sections/delete/${this.currentSectionId}`, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken') // 确保 JWT 令牌被添加到请求头
        }
      })
          .then(response => {
            this.fetchSections(); // 重新获取 sections 以更新页面
            // 关闭编辑模态框并恢复按钮位置
            this.closeEditModal();
            ElMessage.success('删除成功');
          })
          .catch(error => {
            ElMessage.error('权限不足');
          });
    },
    openAddModal() {

      this.showAddModal = true;
      this.addContent = '';
    },
    closeAddModal() {
      this.showAddModal = false;
    },
    saveNewSection() {
      const newSection = {
        text: this.addContent
      };
      axios.post('/api/sections/save', newSection, {
        headers: {
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken') // 确保 JWT 令牌被添加到请求头
        }
      })
          .then(response => {
            this.fetchSections(); // 重新获取 sections 以更新页面
            this.closeAddModal();
            ElMessage.success('添加成功');
          })
          .catch(error => {
            ElMessage.error('添加失败,请检查网络连接或重新登录');
          });
    }
  },
  mounted() {
    this.fetchSections();
    // 新增：获取用户权限
    axios.get('/api/user/role', {
      headers: {
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      }
    })
        .then(response => {
          this.isAdmin = response.data.role === 'ROLE_ADMIN';
        })
        .catch(error => {
          // 添加：显示更详细的错误信息
          if (error.response && error.response.data) {
            // ElMessage.error(`获取用户角色失败: ${error.response.data.message}`);
          } else {
            ElMessage.error('获取用户角色失败，请检查网络连接或重新登录');
          }
        });
  }
}
</script>

<style scoped>
.personal-home {
  background-image: url('../assets/personal.png');
  background-size: cover;
  background-position: center;
  display: flex;
  flex-wrap: wrap;
  min-height: 96vh; 
  width: 96vw; 
  padding: 2vh 2vw;
  overflow: hidden;
  position: relative;
  justify-content: center;
  align-items: flex-start;
  gap: 20px;
}

.section-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 20px;
  width: 100%;
  margin-top: 2vh;
  padding: 0 2vw;
}

.pagination {
  position: fixed; /* 改为fixed定位 */
    bottom: 11px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  gap: 20px;
  z-index: 10;
}

.back-home-button {
  position: fixed;
  
  bottom: 40px;
  right: 20px;
  display: flex;
  gap: 15px;
  z-index: 100;
  transition: opacity 0.3s ease; /* 添加过渡效果 */
}

.section {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  position: relative;
    top: -4vh;
  padding: 20px;
  width: 45%;
  height: 40vh;
  margin: 0;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  overflow-y: auto;
}

.section:hover {
  transform: translateY(-5px);
  background: rgba(255, 255, 255, 0.15);
  box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);
}

.section-text {
      color: #1befe7;
    font-size: 23px;
  line-height: 1.6;
  word-wrap: break-word;
  white-space: pre-wrap;
}

/* 优化滚动条样式 */
.section::-webkit-scrollbar {
  width: 6px;
}

.section::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

.section::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.section::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

.action-button {
  position: relative;
  width: 120px;
  height: 45px;
  background: rgba(4, 177, 255, 0.1);
  border: 1px solid rgba(4, 177, 255, 0.2);
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s ease;
  backdrop-filter: blur(5px);
}

.action-button.add {
  background: rgba(3, 233, 244, 0.1);
  border: 1px solid rgba(3, 233, 244, 0.2);
}

.button-content {
  color: #04b1ff;
  font-size: 18px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 2px;
  z-index: 1;
  transition: all 0.3s ease;
}

.add .button-content {
  color: #03e9f4;
}

.button-glow {
  position: absolute;
  width: 20px;
  height: 100%;
  background: linear-gradient(
    90deg,
    transparent,
    rgba(4, 177, 255, 0.3),
    transparent
  );
  animation: button-glow 2s linear infinite;
  transform: skewX(-45deg);
}

.add .button-glow {
  background: linear-gradient(
    90deg,
    transparent,
    rgba(3, 233, 244, 0.3),
    transparent
  );
}

.button-hover {
  position: absolute;
  inset: 0;
  background: transparent;
  transition: all 0.3s ease;
}

.action-button:hover {
  background: rgba(4, 177, 255, 0.2);
  border-color: #04b1ff;
  transform: translateY(-2px);
}

.action-button.add:hover {
  background: rgba(3, 233, 244, 0.2);
  border-color: #03e9f4;
}

.action-button:hover .button-content {
  color: white;
  text-shadow: 0 0 10px rgba(4, 177, 255, 0.5);
}

.action-button.add:hover .button-content {
  text-shadow: 0 0 10px rgba(3, 233, 244, 0.5);
}

.action-button:hover .button-hover {
  background: linear-gradient(
    45deg,
    transparent,
    rgba(4, 177, 255, 0.1),
    transparent
  );
}

.action-button.add:hover .button-hover {
  background: linear-gradient(
    45deg,
    transparent,
    rgba(3, 233, 244, 0.1),
    transparent
  );
}

@keyframes button-glow {
  0% {
    transform: translateX(-100%) skewX(-45deg);
  }
  100% {
    transform: translateX(200%) skewX(-45deg);
  }
}

.sortpage {
  background: rgba(3, 233, 244, 0.1);
  border: 1px solid rgba(3, 233, 244, 0.3);
  position: relative;
  width: 120px;
  height: 45px;
  text-align: center;
  font-size: 16px;
  letter-spacing: 2px;
  color: #03e9f4;
  text-decoration: none;
  overflow: hidden;
  cursor: pointer;
  border-radius: 8px;
  backdrop-filter: blur(5px);
  transition: all 0.3s ease;
  left: 0;
  right: 0;
  top: 0;
}

.sortpage:hover {
  background: rgba(3, 233, 244, 0.2);
  color: white;
  box-shadow: 
    0 0 5px rgba(3, 233, 244, 0.5),
    0 0 15px rgba(3, 233, 244, 0.3),
    0 0 25px rgba(3, 233, 244, 0.2);
  transform: translateY(-2px);
}

.sortpage:disabled {
  opacity: 0.5;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.back-home-button {
  grid-area: 1 / 2 / 2 / 3;
  display: flex;
      position: absolute;
    bottom: 1vw;
  justify-content: flex-end;
  align-items: flex-start;
}

@media (max-width: 768px) {
  .sortpage {
    width: 100px;
    height: 40px;
    font-size: 16px;
  }

  .back-home-button a {
    width: 80px;
    height: 30px;
    font-size: 14px;
  }
}

.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.7); /* 加深背景色 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: rgba(13, 28, 46, 0.9); /* 改为深色背景 */
  padding: 30px;
  border-radius: 15px;
  width: 600px;
  max-height: 80vh;
  text-align: center;
  border: 1px solid rgba(3, 233, 244, 0.2);
  backdrop-filter: blur(10px);
  box-shadow: 0 0 20px rgba(3, 233, 244, 0.2);
}

textarea {
  width: 93%;
  height: 300px;
  margin-bottom: 20px;
  font-size: 18px;
  resize: vertical;
  background: rgba(255, 255, 255, 0.9);
  border: 1px solid rgba(3, 233, 244, 0.3);
  border-radius: 8px;
  padding: 15px;
  color: #333;
}

.modal-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
}

.modal-buttons button {
  padding: 10px 25px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.3s ease;
  background: rgba(3, 233, 244, 0.1);
  color: #03e9f4;
  border: 1px solid rgba(3, 233, 244, 0.3);
}

.modal-buttons button:hover {
  background: rgba(3, 233, 244, 0.2);
  transform: translateY(-2px);
  box-shadow: 0 0 15px rgba(3, 233, 244, 0.3);
}

.modal-buttons button[style*="background-color: red"] {
  background: rgba(255, 59, 48, 0.1);
  color: #ff3b30;
  border: 1px solid rgba(255, 59, 48, 0.3);
}

.modal-buttons button[style*="background-color: red"]:hover {
  background: rgba(255, 59, 48, 0.2);
  box-shadow: 0 0 15px rgba(255, 59, 48, 0.3);
}
</style>